package com.duk.main;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class CommentsActivity extends Activity {
	private static final int ACTIVITY_IMAGE_CAPTURE = 0;
	private static final int ACTIVITY_IMAGE_CONTENT = 1;
	private static final boolean DEBUG = false;
	
	private TextView getPic = null;
	private ImageView commentPhoto = null;
	private EditText postText = null;
	private Button buttonPost = null;
	public ProgressDialog dialog;

	private Uri originalUri;
	private String dukPicPath = Environment.getExternalStorageDirectory()+"/duk";
	private String dukPicName = null;
	private String text = null;
	private String postURI = "http://192.168.1.123/android/upload/post.php";
	
	@Override  
	 public void onCreate(Bundle savedInstanceStated) {   
		 super.onCreate(savedInstanceStated);   
		 setContentView(R.layout.comments_view); 
		 
		 //判断是否存在文件夹，没有创建
		 File fdir = new File(dukPicPath);
		 if(!fdir.exists()) { 
		       fdir.mkdir(); 
		 }
		 
	     getPic = (TextView)findViewById(R.id.get_pic);
	     commentPhoto = (ImageView)findViewById(R.id.commentphoto);
	     postText = (EditText)findViewById(R.id.post_text);
	     buttonPost = (Button)findViewById(R.id.button_post);
	     
		 findViewById(R.id.LinearLayout01).setBackgroundResource(R.drawable.not_fav);
	     
	     //隐藏控件
	     commentPhoto.setVisibility(8);
	     postText.setVisibility(8);
	     buttonPost.setVisibility(8);
	     
	     //爆料
	     getPic.setOnClickListener(new OnClickListener() {	
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new AlertDialog.Builder(CommentsActivity.this)
					.setTitle("请选择相片!").setIcon(
							android.R.drawable.ic_dialog_info).setItems(
									new String[]{"拍摄一张新相片", "从已有图片中选取"}
									, new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog, int which) {
											// TODO Auto-generated method stub
											switch(which) {
											case 0:
												getPicFromCapture();
												break;
											case 1:
												getPicFromContent();
											default:
												break;
											}
										}
									}
							).setNegativeButton("取消", null).show();
			}
	     });    
	     
	 }
	
	// 调用相机
	private void getPicFromCapture() {
		Intent mIntent = new Intent("android.media.action.IMAGE_CAPTURE");
		// 图片存储路径，可自定义
		dukPicName = null;
		dukPicName = System.currentTimeMillis() + ".jpg";
		File tmpFile = new File(dukPicPath,dukPicName);
		// 获取这个图片的URI
	    originalUri = Uri.fromFile(tmpFile);   //这是个实例变量，方便下面获取图片的时候用
	    mIntent.putExtra(MediaStore.EXTRA_OUTPUT, originalUri);
		mIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
	    startActivityForResult(mIntent, ACTIVITY_IMAGE_CAPTURE);   
	}
	
	//调用相册
	private void getPicFromContent() {
		Intent mIntent= new Intent(Intent.ACTION_GET_CONTENT);
		mIntent.addCategory(Intent.CATEGORY_OPENABLE);
		mIntent.setType("image/*");
		startActivityForResult(mIntent, ACTIVITY_IMAGE_CONTENT);
	}
		
	//通过图片uri取得bitmap
	public Bitmap getBitMap(Uri uri) {	
		 ContentResolver resolver = getContentResolver();
    	 try {
    		 InputStream picStream = resolver.openInputStream(Uri.parse(uri.toString()));
    		 Bitmap postBitmap01 = BitmapFactory.decodeStream(picStream);
    		 ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
    		 if (postBitmap01 != null){
    			 android.graphics.Bitmap.CompressFormat compressformat = android.graphics.Bitmap.CompressFormat.JPEG;
    			 postBitmap01.compress(compressformat, 100, bytearrayoutputstream);
    			 bytearrayoutputstream.toByteArray();
    		 } else {
    			 Toast.makeText(CommentsActivity.this,"bigmap isnull", Toast.LENGTH_SHORT).show();
    		 }
    		 return postBitmap01;
    	 } catch (Exception e) {
    		 if (DEBUG) {
       		  	//Log.i(tag, e);
       		  	Toast.makeText(CommentsActivity.this,e.toString(), Toast.LENGTH_SHORT).show();
       	  	  }
    		 return null;
         }
	}
	
	//取得图片后回调
	 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (resultCode != RESULT_OK) {
        	 return;
         }
         if (requestCode == ACTIVITY_IMAGE_CONTENT) {
        	 // 获得图片的uri
        	 originalUri = data.getData();
        	 commentPhoto.setImageBitmap(getBitMap(originalUri));
         } else {
        	//显示控件
            commentPhoto.setImageDrawable(Drawable.createFromPath(new File(dukPicPath,dukPicName).getAbsolutePath()));
         }        
         commentPhoto.setVisibility(0);
	     postText.setVisibility(0);
	     buttonPost.setVisibility(0); 
 	      
 	      //设置按钮提交事件
 	      buttonPost.setOnClickListener(new OnClickListener() {
 	    	  @Override
 	    	  public void onClick(View v) {
 	    		  text = postText.getText().toString();
 	    		  new AsyncLoader().execute();
 	    	  }
 		  	}); 
	 }
	
	 /**
	  * 直接通过HTTP协议提交数据到服务器,实现表单提交功能
	  * @param actionUrl 上传路径
	  * @param params 请求参数 key为参数名,value为参数值
	  * @param filename 上传文件
	  * @param username 用户名
	  * @param password 密码
	  */
	 private String postImg(String actionUrl,Map<String, String> params, String  filename,String username,String password) {
		 try {
	         String BOUNDARY = "--------------et567z"; //数据分隔线
	         String MULTIPART_FORM_DATA = "Multipart/form-data"; 
	         URL url = new URL(actionUrl);
	         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	         conn.setDoInput(true);//允许输入
	         conn.setDoOutput(true);//允许输出
	         conn.setUseCaches(false);//不使用Cache
	         conn.setRequestMethod("POST");
	         conn.setRequestProperty("Connection", "Keep-Alive");
	         conn.setRequestProperty("Charset", "UTF-8");
	         conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + ";boundary=" + BOUNDARY);
	      //   String usernamePassword=username+":"+password;
	       //  conn.setRequestProperty("Authorization","Basic "+new String(SecBase64.encode(usernamePassword.getBytes())));
	         StringBuilder sb = new StringBuilder(); 
	         //上传的表单参数部分，格式请参考文章
	         for (Map.Entry<String, String> entry : params.entrySet()) {//构建表单字段内容
	             sb.append("--");
	             sb.append(BOUNDARY);
	             sb.append("\r\n");
	             sb.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
	             sb.append(entry.getValue());
	             sb.append("\r\n");
	         }
	         //            System.out.println(sb.toString());
	         DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
	         outStream.write(sb.toString().getBytes());//发送表单字段数据
	              
	         //上传的文件部分，格式请参考文章
	         byte[] content = readFileImage(filename);
	         //System.out.println("content:"+content.toString());
	         StringBuilder split = new StringBuilder();
	         split.append("--");
	         split.append(BOUNDARY);
	         split.append("\r\n");
	         split.append("Content-Disposition: form-data;name=\"file\";filename=\"temp.jpg\"\r\n");
	         split.append("Content-Type: image/jpeg\r\n\r\n");
	         System.out.println(split.toString());
	         outStream.write(split.toString().getBytes());
	         outStream.write(content, 0, content.length);
	         outStream.write("\r\n".getBytes()); 
	         byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//数据结束标志
	         outStream.write(end_data);
	         outStream.flush();    
	         
	         /* 取得Response内容 */
		      InputStream is = conn.getInputStream();
		      int ch;
		      StringBuffer b =new StringBuffer();
		      while( ( ch = is.read() ) != -1 )
		      {
		        b.append( (char)ch );
		      }
		   
		      /* 将Response显示于Dialog */
		     
	          outStream.close();
	          conn.disconnect();
	          
	          return b.toString().trim();
		  } catch(Exception e){
			  return  ""+e;
		  }
	 }

	 public static byte[] readFileImage(String filename) throws IOException {
	     BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(filename));
	     int len = bufferedInputStream.available();
	     byte[] bytes = new byte[len];
	     int r = bufferedInputStream.read(bytes);
	     if (len != r) {
	         bytes = null;
	         throw new IOException("读取文件不正确");
	     }
	     bufferedInputStream.close();
	     return bytes;
	 }
	 	
	 
	/* 
	 * Bitmap类有一compress成员，可以把bitmap保存到一个stream中。
	 */
	 public String saveMyBitmap(Bitmap mBitmap) throws IOException {
		 String filename = System.currentTimeMillis() + ".jpg"; 	 
		 File f = new File(dukPicPath,filename);
	     f.createNewFile();
	     
	     FileOutputStream fOut = null;
	     try {
	    	 fOut = new FileOutputStream(f);   
	     } catch (FileNotFoundException e) {
	         e.printStackTrace();
	     }
	     mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
	     try {
	         fOut.flush();
	     } catch (IOException e) {
	         e.printStackTrace();
	     }
	     try {
	         fOut.close();
	     } catch (IOException e) {
	    	 e.printStackTrace();
	     }
	     return filename;
	  }
	 	
	/*
	setImageBitmap  分别对应着 resource，就是图片有多大然后就显示多大，如果view过小，就会截取它的一部分
	setBackgroundResource ，就是将图片拉伸填充满view
	如果要你的bitmap和view一直，你的view就要设定指定的大小，然后，根据大小放缩，
	给你个放缩的demo把
	//缩放bitmap
	TARGET_WIDTH
	TARGET_HEIGHT 你自己定义
	 */
	 public static Bitmap zoomBitmap(Bitmap target,float widths,float heights)
     {
             int width = target.getWidth();
             int height = target.getHeight();
             Matrix matrix = new Matrix();
             float scaleWidth = ((float)widths)/ width;
             float scaleHeight = ((float)heights)/ height;
             matrix.postScale(scaleWidth, scaleHeight);
             Bitmap result = Bitmap.createBitmap(target, 0, 0, width,   
                 height, matrix, true);   
             return result;
     }
	 
	 /* 显示Dialog的method */
	 private void showDialog(String mess)
	  {
		 
	    new AlertDialog.Builder(CommentsActivity.this).setTitle("Message")
	     .setMessage(formatStr(mess))
	     .setNegativeButton("确定",new DialogInterface.OnClickListener()
	     {
	       public void onClick(DialogInterface dialog, int which)
	       {          
	       }
	     })
	     .show();
	  }
	 

	 private Dialog ExitDialog(Context context) {
	 	AlertDialog.Builder builder = new AlertDialog.Builder(context);
	 	builder.setIcon(R.drawable.icon);
	 	builder.setTitle("生活新报提示");
	 	builder.setMessage("确定退出么?");
	 	builder.setPositiveButton("确定",
	 			new DialogInterface.OnClickListener() {
	 				public void onClick(DialogInterface dialog, int whichButton) {
	 					finish();
	 				}
	 			});
	 	builder.setNegativeButton("取消",
	 			new DialogInterface.OnClickListener() {
	 				public void onClick(DialogInterface dialog, int whichButton) {

	 				}
	 			});
	 	return builder.create();
	 }

	 @Override
	 public boolean onKeyDown(int keyCode, KeyEvent event) {
	 	if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
	 		ExitDialog(CommentsActivity.this).show();
	 		return true;
	 	}
	 	return super.onKeyDown(keyCode, event);
	 }
	 
	 //字符乱码
	 public static String formatStr(String str) {
			if(str == null || str.length() == 0) {
				return "";
			}
			try {
				return new String(str.getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException ex) {
				return "上传出现问题";	
			}
	}
	 
	 
	 
		//继承于AsyncTask
	 class AsyncLoader extends AsyncTask<Object, Object, Object> {

			@Override
			protected Object doInBackground(Object... params) {
		
				 //图片压缩 
		         Bitmap postBitmap02 = zoomBitmap(getBitMap(originalUri),300,200);
		         try {
					dukPicName = saveMyBitmap( postBitmap02);
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				Map<String, String> map = new HashMap<String, String>();
 	            map.put("par", text);//改成自己的key
 	            return postImg(postURI,map,dukPicPath+"/"+dukPicName,"帐号名字","密码");				
			}

			@Override
			protected void onCancelled() {
				// TODO Auto-generated method stub
				super.onCancelled();
			}

			@Override
			protected void onPostExecute(Object result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				setProgressBarIndeterminateVisibility(false);
				dialog.dismiss();			
				showDialog(result.toString());
			}

			@Override
			protected void onPreExecute() {
				// TODO Auto-generated method stub
				super.onPreExecute();
				dialog = new ProgressDialog(CommentsActivity.this);
				dialog.setCancelable(false);
				dialog.setTitle("图片上传中...");
				dialog.setMessage("上传中,请稍候...");
				dialog.show();
			}

			@Override
			protected void onProgressUpdate(Object... values) {
				// TODO Auto-generated method stub
				super.onProgressUpdate(values);
			} 
	 }
	 
}
